<template>
  <div class="process">
    <div v-if="$store.state.apim.step === 5" class="outMsgConfig">
      <el-form v-if="isDB" ref="outMsgConfigRef" class="queryForm flex" :inline="true" :model="outMsgConfigFrom" :rules="outMsgRule">
        <!-- 根据第二步返回 -->
        <el-form-item :label="translateTitle('Dams.ProcssConfig.报文层级')">
          <el-input v-model="currentLevel" disabled />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.目标调用表名')" prop="WEB_TABLE_NAME">
          <el-input v-model="outMsgConfigFrom.WEB_TABLE_NAME" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.是否有子层级')">
          <el-switch v-model="outMsgConfigFrom.isChild" disabled size="large" />
        </el-form-item>
      </el-form>
      <div v-if="!isDB" class="msgSample">
        <el-descriptions border :column="4" direction="vertical" size="large">
          <el-descriptions-item :label="translateTitle('Dams.ProcssConfig.报文样例')">
            <CodeEditor v-model="msgValue" />
          </el-descriptions-item>
        </el-descriptions>
        <el-button class="analysis" type="primary" @click="MsgAnalysis">{{ translateTitle('Dams.ProcssConfig.解析') }}>></el-button>
        <el-descriptions border :column="4" direction="vertical" size="large">
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <p>{{ translateTitle('Dams.ProcssConfig.报文样例结果') }}</p>
                <p>
                  <el-button type="info" @click="XMLFormat">{{ translateTitle('Dams.ProcssConfig.XML格式化') }}</el-button>
                  <el-button type="info" @click="JSONFormat">{{ translateTitle('Dams.ProcssConfig.JSON格式化') }}</el-button>
                </p>
              </div>
            </template>
            <CodeEditor v-model="msgResultValue" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-divider border-style="dashed" />
      <!-- <div v-if="isDB">
        <div class="flex justify-between" style="padding: 10px 5px; background-color: #f4f5f7; color: #4e5969">
          <span>报文解析</span>
          <el-button type="primary" @click="analysis">{{ translateTitle('Dams.ProcssConfig.解析') }}</el-button>
        </div>
        <div>
          <CodeEditor v-model="outgoingMessage" />
        </div>
      </div> -->
      <!-- DB -->
      <vxe-table v-if="isDB" ref="outMsgConfigTableRef" class="outMsgConfigTable" :data="outMsgConfigData" height="400" show-overflow size="mini">
        <!-- 根据第二步返回的得到 -->
        <vxe-column field="STD_FIELD" :title="translateTitle('Dams.ProcssConfig.来源字段名')">
          <template #default="{ row }">
            <vxe-input v-if="isDB" v-model="row.STD_FIELD" size="small" />
            <p v-else>{{ row.STD_FIELD }}</p>
          </template>
        </vxe-column>
        <vxe-column field="WEB_FIELD" :title="translateTitle('Dams.ProcssConfig.目标字段名')">
          <template #default="{ row }">
            <vxe-input v-model="row.WEB_FIELD" size="small" />
          </template>
        </vxe-column>
        <vxe-column
          v-if="currentLevel === translateTitle('Dams.ProcssConfig.第一层')"
          field="KEY_FLAG"
          :title="translateTitle('Dams.ProcssConfig.是否主键')"
        >
          <template #default="{ row }">
            <el-switch v-model="row.KEY_FLAG" size="small" />
          </template>
        </vxe-column>
        <vxe-column
          v-if="currentLevel === translateTitle('Dams.ProcssConfig.第一层')"
          field="UPDATE_FLAG"
          :title="translateTitle('Dams.ProcssConfig.是否允许更新')"
        >
          <template #default="{ row }">
            <el-switch v-model="row.UPDATE_FLAG" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="WEB_DEFAULT" :title="translateTitle('Dams.ProcssConfig.默认值')">
          <template #default="{ row }">
            <vxe-input v-model="row.WEB_DEFAULT" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="WEB_DATA_FORMAT" :title="translateTitle('Dams.ProcssConfig.字段格式化')">
          <template #default="{ row }">
            <vxe-input v-model="row.WEB_DATA_FORMAT" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="WEB_DATA_TYPE" :title="translateTitle('Dams.ProcssConfig.字段类型')">
          <template #default="{ row }">
            <vxe-select v-model="row.WEB_DATA_TYPE" size="small" transfer>
              <vxe-option v-for="item in msgTypes" :key="item.value" :label="item.key" :value="item.value" />
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="ACTIVE_FLAG" :title="translateTitle('Dams.ProcssConfig.激活标志')">
          <template #default="{ row }">
            <el-switch v-model="row.ACTIVE_FLAG" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="WEB_DATA_WIDTH" :title="translateTitle('Dams.ProcssConfig.字段长度')">
          <template #default="{ row }">
            <vxe-input v-model="row.WEB_DATA_WIDTH" size="small" />
          </template>
        </vxe-column>
        <vxe-column class="operate" :title="translateTitle('Dams.ProcssConfig.操作')" width="170px">
          <template #default="{ row }">
            <el-button :style="{ padding: 0, margin: 2 }" text type="text" @click="outMsgConfigAdd(row)">
              <vui-icon icon="add-circle-line" />
              {{ translateTitle('Dams.ProcssConfig.新增') }}
            </el-button>
            <el-button :style="{ padding: 0, margin: 2 }" type="text" @click="outMsgConfigCopy(row)">
              <vui-icon icon="file-copy-line" />
              {{ translateTitle('Dams.ProcssConfig.复制') }}
            </el-button>
            <el-button style="color: #f56c6c" :style="{ padding: 0, margin: 2 }" type="text" @click="outMsgConfigDel(row)">
              <vui-icon icon="delete-bin-line" />
              {{ translateTitle('Dams.ProcssConfig.删除') }}
            </el-button>
          </template>
        </vxe-column>
        <template #empty>
          <el-button :style="{ padding: 0, margin: 2 }" text type="text" @click="outMsgConfigAdd(row)">
            <vui-icon icon="add-circle-line" />
            {{ translateTitle('Dams.ProcssConfig.新增') }}
          </el-button>
        </template>
      </vxe-table>
      <!-- 非DB -->
      <div v-if="!isDB">
        <vxe-table
          v-for="(table, index) in DBlevelList"
          :key="table.MESSAGE_TYPE"
          :ref="'DBlevel' + index"
          class="outMsgConfigTable"
          :data="notDBList[index]"
          size="mini"
        >
          <vxe-column field="STD_FIELD" :title="translateTitle('Dams.ProcssConfig.来源字段名')">
            <template #default="{ row }">
              <vxe-input v-model="row.STD_FIELD" :disabled="!row.isDisabled" size="small" />
            </template>
          </vxe-column>
          <!-- <vxe-column field="MESSAGE_FILED" title="来源字段名" /> -->
          <vxe-column field="MESSAGE_TYPE" :title="translateTitle('Dams.ProcssConfig.报文层级')" />
          <!-- <vxe-column field="XPATH_EXPRESS" title="XPATH表达式" /> -->
          <vxe-column field="XPATH_EXPRESS" :title="translateTitle('Dams.ProcssConfig.XPATH表达式')">
            <template #default="{ row }">
              <vxe-input v-model="row.XPATH_EXPRESS" :disabled="!row.isDisabled" size="small" />
            </template>
          </vxe-column>
          <vxe-column field="MESSAGE_FILED" :title="translateTitle('Dams.ProcssConfig.目标字段名')">
            <template #default="{ row, rowIndex }">
              <el-select v-model="row.MESSAGE_FILED" size="small" transfer @change="targetFieldChange(row.MESSAGE_FILED, index, rowIndex)">
                <el-option v-for="item in targetField[index]" :key="item.name" :label="item.name" :value="item.name">
                  <span v-if="notDBList[index].some((x) => x.MESSAGE_FILED === item.name)" style="color: #0dbc79">{{ item.name }}</span>
                </el-option>
              </el-select>
              <!-- <vxe-input v-else v-model="row.MESSAGE_FILED" size="small" @input="targetFieldChange(row.MESSAGE_FILED, index, rowIndex)" /> -->
            </template>
          </vxe-column>
          <vxe-column field="IS_TRANSFER_FIELD" :title="translateTitle('Dams.ProcssConfig.是否传播字段')">
            <template #default="{ row }">
              <el-switch v-model="row.IS_TRANSFER_FIELD" size="small" />
            </template>
          </vxe-column>
          <vxe-column field="NODE_VALUE" :title="translateTitle('Dams.ProcssConfig.默认值')">
            <template #default="{ row }">
              <vxe-input v-model="row.NODE_VALUE" size="small" />
            </template>
          </vxe-column>
          <vxe-column field="DATA_TYPE" :title="translateTitle('Dams.ProcssConfig.字段类型')">
            <template #default="{ row }">
              <el-select v-model="row.DATA_TYPE" size="small" transfer>
                <el-option v-for="item in msgTypes" :key="item.value" :label="item.key" :value="item.value" />
              </el-select>
            </template>
          </vxe-column>
          <vxe-column field="ACTIVE_FLAG" :title="translateTitle('Dams.ProcssConfig.激活标志')">
            <template #default="{ row }">
              <el-switch v-model="row.ACTIVE_FLAG" size="small" />
            </template>
          </vxe-column>
          <vxe-column field="DATA_WIDTH" :title="translateTitle('Dams.ProcssConfig.字段长度')">
            <template #default="{ row }">
              <vxe-input v-model="row.DATA_WIDTH" size="small" />
            </template>
          </vxe-column>
          <vxe-column class="operate" :title="translateTitle('Dams.ProcssConfig.操作')" width="170px">
            <template #default="{ row }">
              <el-button :style="{ padding: 0, margin: 2 }" text type="text" @click="notDBoutMsgConfigAdd(row, index)">
                <vui-icon icon="add-circle-line" />
                {{ translateTitle('Dams.ProcssConfig.新增') }}
              </el-button>
              <el-button :style="{ padding: 0, margin: 2, color: '#f56c6c' }" text type="text" @click="notDBoutMsgConfigDel(row, index)">
                <vui-icon icon="delete-bin-line" />
                {{ translateTitle('Dams.ProcssConfig.删除') }}
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <div v-if="$store.state.apim.step === 6 && isCallBack" class="callbackConfig">
      <el-form ref="callbackConfigRef" :inline="true" label-width="100px" :model="callbackConfigFrom" :rules="callbackConfigRule">
        <el-form-item :label="translateTitle('Dams.ProcssConfig.回调接口ID')" prop="RETURN_MESSAGE_ID">
          <el-input v-model="callbackConfigFrom.RETURN_MESSAGE_ID" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.回调前置条件')" prop="RETURN_CONDITION">
          <el-input v-model="callbackConfigFrom.RETURN_CONDITION" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
        <el-form-item v-for="item in customParas" :key="item.value" :label="item.label">
          <el-input v-model="callbackConfigFrom[item.value]" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="$store.state.apim.step === 7" class="ruleConfig">
      <el-form class="fff" :inline="true" label-width="120px" :model="ruleConfigFrom">
        <el-form-item :label="translateTitle('Dams.ProcssConfig.验证类型')">
          <el-select v-model="ruleConfigFrom.VALUE_STR01" clearable>
            <el-option v-for="item in signTypes" :key="item" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="App-key">
          <el-input v-model="ruleConfigFrom.VALUE_STR02" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
        <el-form-item label="App-secret">
          <el-input v-model="ruleConfigFrom.VALUE_STR03" :placeholder="translateTitle('Dams.ProcssConfig.请输入')" />
        </el-form-item>
        <el-form-item label="Content-type">
          <el-select v-model="ruleConfigFrom.contentType" clearable>
            <el-option v-for="item in contentTypes" :key="item" :label="item.key" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.规则校验')">
          <el-select v-model="ruleMessage.RULE_ID" clearable multiple>
            <el-option v-for="item in ruleVerificationQuery" :key="item" :label="item.RULE_NAME" :value="item.RULE_ID" />
          </el-select>
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.数据过滤规则')">
          <vxe-table ref="dataFilterRuleRef" border :data="dataFilterRuleList" :row-config="{ isHover: true }" show-header-overflow show-overflow>
            <vxe-column field="MESSAGE_TYPE" :title="translateTitle('Dams.ProcssConfig.消息层级')">
              <template #default="{ row }">
                <vxe-select v-model="row.MESSAGE_TYPE" size="small" transfer>
                  <vxe-option v-for="item in msgLevel" :key="item.value" :label="item.key" :value="item.value" />
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="ACTIVE_FLAG" :title="translateTitle('Dams.ProcssConfig.是否激活')">
              <template #default="{ row }">
                <el-switch v-model="row.ACTIVE_FLAG" size="small" />
              </template>
            </vxe-column>
            <vxe-column field="SN" :title="translateTitle('Dams.ProcssConfig.执行顺序')">
              <template #default="{ row }">
                <vxe-input v-model="row.SN" size="small" type="number" />
              </template>
            </vxe-column>
            <vxe-column field="SQLTEXT" :title="translateTitle('Dams.ProcssConfig.过滤表达式')">
              <template #default="{ row }">
                <vxe-input v-model="row.SQLTEXT" size="small" />
              </template>
            </vxe-column>
            <vxe-column align="center" field="" :title="translateTitle('Dams.ProcssConfig.操作')" width="140px">
              <template #default="{ row }">
                <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="filterRuleAdd(-1)" />
                <vui-icon icon="delete-bin-line" style="color: #f56c6c; font-size: 22px" @click="filterRuleDel(row)" />
              </template>
            </vxe-column>
            <template #empty>
              <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="filterRuleAdd()" />
            </template>
          </vxe-table>
        </el-form-item>
        <el-form-item
          v-if="
            $store.state.apim.requiredForm.stepTwoDATA_ACTION == '14' ||
            $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' ||
            $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
          "
          :label="
            $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
              ? '文件配置参数'
              : translateTitle('Dams.ProcssConfig.邮件摘要参数')
          "
        >
          <vxe-table ref="msgDigestParamsRef" border :data="msgDigestParamsList" :row-config="{ isHover: true }" show-header-overflow show-overflow>
            <vxe-column
              field="VALUE_STR01"
              :title="
                $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
                  ? '获取文件key1'
                  : translateTitle('Dams.ProcssConfig.邮件主题')
              "
            >
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR01" size="small" />
              </template>
            </vxe-column>
            <vxe-column
              field="VALUE_STR02"
              :title="
                $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
                  ? '获取文件key2'
                  : translateTitle('Dams.ProcssConfig.邮件正文')
              "
            >
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR02" size="small" />
              </template>
            </vxe-column>
            <vxe-column
              field="VALUE_STR03"
              :title="
                $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
                  ? '获取文件key3'
                  : translateTitle('Dams.ProcssConfig.收件人')
              "
            >
              <template #header v-if="$store.state.apim.requiredForm.stepTwoDATA_ACTION == '14'">
                <span>{{ translateTitle('Dams.ProcssConfig.收件人') }}</span>
                <el-popover :content="translateTitle('Dams.ProcssConfig.多个收件人用进行分隔')" placement="top-start" trigger="hover" :width="200">
                  <template #reference>
                    <vui-icon icon="question-line" style="color: #409eff" />
                  </template>
                </el-popover>
              </template>
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR03" size="small" />
              </template>
            </vxe-column>
            <vxe-column
              field="VALUE_STR04"
              :title="
                $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
                  ? '获取文件key4'
                  : translateTitle('Dams.ProcssConfig.是否发送附件')
              "
            >
              <template #default="{ row }">
                <el-switch v-model="row.VALUE_STR04" size="small" />
              </template>
            </vxe-column>
            <vxe-column
              field="VALUE_STR05"
              :title="
                $store.state.apim.requiredForm.stepTwoDATA_ACTION == '51' || $store.state.apim.requiredForm.stepTwoDATA_ACTION == '52'
                  ? '获取文件key5'
                  : translateTitle('Dams.ProcssConfig.正文占位符显示最大数')
              "
            >
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR05" size="small" type="number" />
              </template>
            </vxe-column>
            <vxe-column align="center" field="" :title="translateTitle('Dams.ProcssConfig.操作')" width="140px">
              <template #default="{ row }">
                <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="msgDigestParamsAdd(-1)" />
                <vui-icon icon="delete-bin-line" style="color: #f56c6c; font-size: 22px" @click="msgDigestParamsDel(row)" />
              </template>
            </vxe-column>
            <template #empty>
              <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="msgDigestParamsAdd()" />
            </template>
          </vxe-table>
        </el-form-item>
        <el-form-item v-if="isDB" :label="translateTitle('Dams.ProcssConfig.后置SP参数配置')">
          <vxe-table ref="httpHeaderRef" border :data="postSp" :row-config="{ isHover: true }" show-header-overflow show-overflow>
            <vxe-column field="VALUE_STR01" :title="translateTitle('Dams.ProcssConfig.后置SP名')">
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR01" clearable size="small" />
              </template>
            </vxe-column>
            <vxe-column field="VALUE_STR02" :title="translateTitle('Dams.ProcssConfig.后置SP参数')">
              <template #header>
                <span>
                  <span>
                    <span>{{ translateTitle('Dams.ProcssConfig.后置SP参数') }}</span>
                    <span style="font-size: 12px; color: #af3636">
                      <span>
                        <el-tooltip effect="dark" placement="top" style="diaplay: inline">
                          <template
                            #content
                            :style="{
                              color: '#000',
                            }"
                          >
                            {{ translateTitle('Dams.ProcssConfig.SP参数支持三种类型') }}
                          </template>
                          <vui-icon icon="question-fill" />
                        </el-tooltip>
                      </span>
                    </span>
                  </span>
                </span>
              </template>
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR02" clearable size="small" />
              </template>
            </vxe-column>
            <vxe-column field="VALUE_STR03" :title="translateTitle('Dams.ProcssConfig.后置SP转义标识')">
              <template #header>
                <span>
                  <span>
                    <span>{{ translateTitle('Dams.ProcssConfig.后置SP转义标识') }}</span>
                    <span style="font-size: 12px; color: #af3636">
                      <span>
                        <el-tooltip effect="dark" placement="top" style="diaplay: inline">
                          <template
                            #content
                            :style="{
                              color: '#000',
                            }"
                          >
                            {{ translateTitle('Dams.ProcssConfig.SP响应结果转义模板') }}
                          </template>
                          <vui-icon icon="question-fill" />
                        </el-tooltip>
                      </span>
                    </span>
                  </span>
                </span>
              </template>
              <template #default="{ row }">
                <vxe-input v-model="row.VALUE_STR03" clearable size="small" />
              </template>
            </vxe-column>
          </vxe-table>
        </el-form-item>
        <div style="display: flex">
          <el-form-item :label="`http-header ${translateTitle('Dams.ProcssConfig.参数')}`">
            <vxe-table ref="httpHeaderRef" border :data="httpHeaderList" :row-config="{ isHover: true }" show-header-overflow show-overflow>
              <vxe-column field="VALUE_STR01" title="key">
                <template #default="{ row }">
                  <vxe-input v-model="row.VALUE_STR01" size="small" />
                </template>
              </vxe-column>
              <vxe-column field="VALUE_STR02" title="value">
                <template #default="{ row }">
                  <vxe-input v-model="row.VALUE_STR02" size="small" />
                </template>
              </vxe-column>
              <vxe-column align="center" field="" :title="translateTitle('Dams.ProcssConfig.操作')" width="120px">
                <template #default="{ row }">
                  <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="httpHeaderAdd(-1)" />
                  <vui-icon icon="delete-bin-line" style="color: #f56c6c; font-size: 22px" @click="httpHeaderDel(row)" />
                </template>
              </vxe-column>
              <template #empty>
                <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="httpHeaderAdd()" />
              </template>
            </vxe-table>
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ProcssConfig.命名空间')">
            <vxe-table ref="spaceListRef" border :data="spaceList" :row-config="{ isHover: true }" show-header-overflow show-overflow>
              <vxe-column field="VALUE_STR01" title="key">
                <template #default="{ row }">
                  <vxe-input v-model="row.VALUE_STR01" size="small" />
                </template>
              </vxe-column>
              <vxe-column field="VALUE_STR02" title="value">
                <template #default="{ row }">
                  <vxe-input v-model="row.VALUE_STR02" size="small" />
                </template>
              </vxe-column>
              <vxe-column align="center" field="" :title="translateTitle('Dams.ProcssConfig.操作')" width="120px">
                <template #default="{ row }">
                  <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="spaceAdd(-1)" />
                  <vui-icon icon="delete-bin-line" style="color: #f56c6c; font-size: 22px" @click="spaceDel(row)" />
                </template>
              </vxe-column>
              <template #empty>
                <vui-icon icon="add-circle-line" style="color: #409eff; font-size: 22px; padding-right: 10px" @click="spaceAdd()" />
              </template>
            </vxe-table>
          </el-form-item>
        </div>
        <el-form-item :label="translateTitle('Dams.ProcssConfig.报文替换模板')">
          <el-input v-model="ruleConfigFrom.replaceTemp" type="textarea" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="$store.state.apim.step === 8" class="success">
      <p class="img"><img alt="" src="@/assets/dams_images/19096.png" /></p>
      <p class="title">{{ translateTitle('Dams.ProcssConfig.发布成功') }}</p>
      <p v-if="url" class="content">
        {{ `${translateTitle('Dams.ProcssConfig.接口发布成功')}，${translateTitle('Dams.ProcssConfig.生成的地址为')}：${url} ` }}
      </p>
      <p v-else class="content">
        {{ `${translateTitle('Dams.ProcssConfig.接口发布成功')}，${translateTitle('Dams.ProcssConfig.生成的定时任务调度为')}：` }}
        <span style="color: #3270ff">{{ MESSAGE_GROUP_ID }}_{{ MESSAGE_ID }}</span>
        {{
          `（${translateTitle('Dams.ProcssConfig.默认每十秒执行一次')}，${translateTitle('Dams.ProcssConfig.如需修改')}，${translateTitle(
            'Dams.ProcssConfig.请前往定时器配置页面进行修改'
          )}！）`
        }}
      </p>
    </div>
  </div>
  <div class="buttonGroup">
    <div v-if="$store.state.apim.step === 5 || $store.state.apim.step === 6">
      <el-button @click="backClick">{{ translateTitle('Dams.ProcssConfig.上一步') }}</el-button>
      <el-button type="primary" @click="nextClick" :loading="nextLoading">{{ translateTitle('Dams.ProcssConfig.下一步') }}</el-button>
    </div>
    <div v-if="$store.state.apim.step === 7">
      <el-button @click="backClick">{{ translateTitle('Dams.ProcssConfig.上一步') }}</el-button>
      <el-button type="primary" @click="publicClick">{{ translateTitle('Dams.ProcssConfig.发布接口') }}</el-button>
    </div>
    <div v-if="$store.state.apim.step === 8" style="margin-top: 40px">
      <el-button @click="reconfigClick">{{ translateTitle('Dams.ProcssConfig.重新配置') }}</el-button>
      <el-button v-if="url" @click="onPostmanClick">接口测试</el-button>
    </div>
    <el-dialog v-model="postmanDialog" title="postman" width="80%">
      <PostManDialog v-if="postmanDialog" :apiurl="url" />
    </el-dialog>
  </div>
</template>

<script>
  import { translateTitle } from '@/utils/i18n'
  import CodeEditor from '@/project/dams/components/codeEditor.vue'
  import { apimRequest } from '../../../api/home'
  import cloneDeep from 'lodash/cloneDeep'
  import { GFCD } from '@/utils/utils'
  import PostManDialog from './components/postManDialog.vue'
  export default {
    components: {
      CodeEditor,
      PostManDialog,
    },
    data() {
      return {
        nextLoading: false,
        postmanDialog: false,
        postSp: [{ VALUE_STR01: '', VALUE_STR02: '', VALUE_STR03: '' }],
        notDBList: [],
        MESSAGE_ID: '',
        MESSAGE_GROUP_ID: '',
        outMsgConfigFrom: { WEB_TABLE_NAME: '' },
        outMsgConfigData: [],
        totalLevels: [], //总层级
        currentLevel: translateTitle('Dams.ProcssConfig.第一层'),
        levelParamsList: [],
        currentIndex: 0,
        DBlevelList: [], //层级和来源字段信息
        msgResultValue: '', //报文样例结果
        msgValue: '', //报文样例
        tableList: [],
        targetField: [],
        structureConfigMap: [],
        msgTypes: [],
        callbackConfigFrom: {},
        messageMappingList: [], //第五步DB回显数据
        messageXmlList: [], //第五步非DB回显数据
        targetMappingList: [], //筛选后的第五步DB回显数据
        dbData: {}, //第五步DB提交的数据
        dbList: [], //第五步DB数据list
        isDB: true, //由第四步返回
        customParas: [
          { label: `${translateTitle('Dams.ProcssConfig.自定义参数')}1`, value: 'RETURN_PARAM1' },
          { label: `${translateTitle('Dams.ProcssConfig.自定义参数')}2`, value: 'RETURN_PARAM2' },
          { label: `${translateTitle('Dams.ProcssConfig.自定义参数')}3`, value: 'RETURN_PARAM3' },
          { label: `${translateTitle('Dams.ProcssConfig.自定义参数')}4`, value: 'RETURN_PARAM4' },
          { label: `${translateTitle('Dams.ProcssConfig.自定义参数')}5`, value: 'RETURN_PARAM5' },
        ],
        isCallBack: false,
        ruleConfigFrom: {},
        ruleVerificationQuery: [],
        ruleMessage: { RULE_ID: [] },
        httpHeaderList: [],
        dataFilterRuleList: [], //过滤规则数据
        msgDigestParamsList: [], //邮件摘要参数
        msgLevel: [], //消息层级
        signTypes: [], //验证类型
        contentTypes: [], //content-Type
        spaceList: [],

        outMsgRule: {
          WEB_TABLE_NAME: [{ required: true, message: translateTitle('Dams.ProcssConfig.请输入表名'), trigger: 'blur' }],
        },
        callbackConfigRule: {
          RETURN_MESSAGE_ID: [{ required: true, message: translateTitle('Dams.ProcssConfig.请输入回调接口ID'), trigger: 'blur' }],
        },
        step: 1,
        url: '',
      }
    },
    watch: {
      'outMsgConfigFrom.WEB_TABLE_NAME': function (val) {
        this.outMsgConfigFrom.WEB_TABLE_NAME = val
      },
    },
    async created() {
      this.MESSAGE_GROUP_ID = this.$store.state.apim.requiredForm.MESSAGE_GROUP_ID
      this.MESSAGE_ID = this.$store.state.apim.requiredForm.MESSAGE_ID
      this.DBlevelList = this.$store.state.apim.requiredForm.DBlevelList
      this.totalLevels = this.$store.state.apim.requiredForm.hierarchyList
      if (this.DBlevelList.length === 0 || !this.DBlevelList[0].JNDI_NAME) {
        this.DBlevelList = JSON.parse(sessionStorage.getItem('dblist'))
      }
      if (this.totalLevels.length === 0) {
        this.totalLevels = JSON.parse(sessionStorage.getItem('totalLevels'))
      }

      this.isDB = this.$store.state.apim.requiredForm.DATA_ACTION === '40' ?? true
      this.outMsgConfigFrom.isChild = this.DBlevelList && this.DBlevelList.length > 1 ? true : false
      //DB回显表名
      if (this.$store.state.apim.queryData.stdTableList) {
        let dataform = this.$store.state.apim.queryData.stdTableList
        let From = dataform.find((x) => {
          return x.MESSAGE_TYPE === this.DBlevelList[this.currentIndex].value
        })
        if (From) {
          this.outMsgConfigFrom.WEB_TABLE_NAME = From.WEB_TABLE_NAME
        }
      }
      let tabledata = []
      if (this.DBlevelList && this.DBlevelList.length > 0) {
        //获取来源字段名
        tabledata = this.DBlevelList[0].JNDI_NAME
      }
      if (this.isDB) {
        //设置新增时DB的来源字段名和目标字段名
        tabledata.forEach((x, i) => {
          this.outMsgConfigData[i] = { STD_FIELD: x, WEB_FIELD: x, ACTIVE_FLAG: true, WEB_DATA_TYPE: 'STRING' }
        })
        //第五步DB回显
        if (this.$store.state.apim.queryData.messageMappingList && this.$store.state.apim.queryData.messageMappingList.length > 0) {
          this.feedBack()
        }
      } else {
        //非DB
        if (this.DBlevelList && this.DBlevelList.length > 0) {
          this.DBlevelList.forEach((table, index) => {
            this.notDBList.push([])
            //新增时的来源字段和目标字段
            table.JNDI_NAME.forEach((x) => {
              this.notDBList[index].push({ STD_FIELD: x, ACTIVE_FLAG: true, MESSAGE_TYPE: table.MESSAGE_TYPE, XPATH_EXPRESS: '' })
            })
            //编辑回显
            if (this.$store.state.apim.queryData.messageXmlList) {
              this.messageXmlList = cloneDeep(this.$store.state.apim.queryData.messageXmlList)
              //筛选符合条件的回显
              let nottargetList = this.messageXmlList.filter(
                (item) => table.JNDI_NAME.some(() => item.MESSAGE_TYPE === table.MESSAGE_TYPE) && item.ADAPTER_TYPE === 'O'
              )

              nottargetList.forEach((item) => {
                table.JNDI_NAME.forEach((x, i) => {
                  if (x === item.STD_FIELD && item.MESSAGE_TYPE === table.MESSAGE_TYPE) {
                    this.notDBList[index][i] = item
                  }
                })
              })
              //合并去重
              this.notDBList[index] = this.notDBList[index].concat(nottargetList)
              let obj = {}
              this.notDBList[index] = this.notDBList[index].reduce((pre, cur) => {
                if (!obj[cur.STD_FIELD]) {
                  obj[cur.STD_FIELD] = true
                  pre.push(cur)
                }
                return pre
              }, [])

              this.notDBList[index].forEach((x) => {
                //字符串转boolean
                if (typeof x.ACTIVE_FLAG == 'string') {
                  x.ACTIVE_FLAG = x.ACTIVE_FLAG && x.ACTIVE_FLAG == 'Y' ? true : false
                }
                if (typeof x.IS_TRANSFER_FIELD == 'string') {
                  x.IS_TRANSFER_FIELD = x.IS_TRANSFER_FIELD && x.IS_TRANSFER_FIELD == 'Y' ? true : false
                }
              })
            } else {
              //   // this.notDBList[index].forEach((x) => {
              //   //   x.XPATH_EXPRESS = './' + x.MESSAGE_FILED
              //   // })
            }
          })
        }
      }
      this.isCallBack = this.$store.state.apim.requiredForm.isCallBack === 'Y' ?? true
      this.configSetting = GFCD('apim')

      try {
        let { data } = await apimRequest(`${this.configSetting.domain}/apim/config/stream/list/dataType`, {
          'Content-Type': 'application/json',
        })
        this.msgTypes = data
      } catch (err) {
        console.log(err)
      }
    },
    beforeUnmount() {
      sessionStorage.setItem('dblist', JSON.stringify(this.DBlevelList))
      sessionStorage.setItem('totalLevels', JSON.stringify(this.totalLevels))
    },
    methods: {
      onPostmanClick() {
        this.postmanDialog = true
      },
      translateTitle,
      /****************************出向报文设置***************************/
      //第五步DB回显
      feedBack() {
        //DB的回显数据源
        this.messageMappingList = cloneDeep(this.$store.state.apim.queryData.messageMappingList)
        this.messageMappingList = this.messageMappingList.filter((x) => {
          return x.MESSAGE_TYPE === this.DBlevelList[this.currentIndex].value
        })
        //来源字段回显
        this.DBlevelList[this.currentIndex].JNDI_NAME.forEach((x, i) => {
          this.outMsgConfigData[i].STD_FIELD = x
        })
        //匹配的回显
        this.messageMappingList.forEach((item) => {
          this.outMsgConfigData.forEach((x, i) => {
            if (x.STD_FIELD === item.STD_FIELD && item.MESSAGE_TYPE === this.DBlevelList[this.currentIndex].value) {
              this.outMsgConfigData[i] = item
            }
          })
        })
        //合并去重
        this.outMsgConfigData = this.outMsgConfigData.concat(this.messageMappingList)
        let obj = {}
        this.outMsgConfigData = this.outMsgConfigData.reduce((pre, cur) => {
          if (!obj[cur.STD_FIELD]) {
            obj[cur.STD_FIELD] = true
            pre.push(cur)
          } else {
            pre.forEach((x) => {
              if (x.STD_FIELD === cur.STD_FIELD && x.WEB_FIELD !== cur.WEB_FIELD) {
                x.WEB_FIELD += ',' + cur.WEB_FIELD
              }
            })
          }

          return pre
        }, [])
        //boolean转字符串
        this.outMsgConfigData.forEach((x) => {
          x.ACTIVE_FLAG = x.ACTIVE_FLAG && x.ACTIVE_FLAG == 'Y' ? (x.ACTIVE_FLAG = true) : (x.ACTIVE_FLAG = false)
          x.KEY_FLAG = x.KEY_FLAG && x.KEY_FLAG == 'Y' ? (x.KEY_FLAG = true) : (x.KEY_FLAG = false)
          x.UPDATE_FLAG = x.UPDATE_FLAG && x.UPDATE_FLAG == 'Y' ? (x.UPDATE_FLAG = true) : (x.UPDATE_FLAG = false)
        })
        return this.outMsgConfigData
      },
      getXpath(r, Hpath) {
        let str = ''
        if (r.level == 'H') {
          str = '//' + r.name
        } else {
          str = r.xpath.replace(Hpath, '.')
        }
        return str
      },
      //报文解析
      async MsgAnalysis() {
        try {
          let { data: analysis } = await apimRequest(
            `${this.configSetting.domain}/apim/config/stream/inverse/analysis`,
            JSON.stringify({ message: this.msgValue }),
            {
              'Content-Type': 'application/json',
            }
          )
          this.msgResultValue = analysis.outgoingResult
          let { data: message } = await apimRequest(
            `${this.configSetting.domain}/apim/config/stream/parse/message`,
            JSON.stringify({ message: this.msgValue }),
            {
              'Content-Type': 'application/json',
            }
          )
          message.forEach((r) => {
            if (message.find((el) => el.name == r.parent) && message.find((el) => el.name == r.parent).level && r.isNode == 'N') {
              r.level = message.find((el) => el.name == r.parent).level
            }
          })
          let filt = message.filter((item) => {
            return item.isNode === 'N'
          })
          let list = message.filter((item) => {
            return item.isNode === 'Y' && item.level && item.level !== null
          })
          this.tableList = []
          list.forEach((x, i) => {
            this.tableList[i] = { MESSAGE_TYPE: x.level }
          })
          this.DBlevelList.forEach((table, index) => {
            this.targetField[index] = filt.filter((x) => {
              return x.level === table.MESSAGE_TYPE
            })
          })
          let hpath = message.find((el) => el.level == 'H' && el.isNode == 'Y').xpath
          this.structureConfigMap = message
            .filter((item) => {
              return item.isNode === 'Y' && item.level
            })
            .map((x, i) => {
              return (this.structureConfigMap[i] = {
                MESSAGE_TYPE: x.level,
                XPATH_EXPRESS: this.getXpath(x, hpath),
              })
            })
        } catch (err) {
          console.log(err)
        }
      },
      //XML格式化
      showXml(text) {
        //去掉多余的空格
        text =
          '\n' +
          text
            .replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
              return name + ' ' + props.replace(/\s+(\w+=)/g, ' $1')
            })
            .replace(/>\s*?</g, '>\n<')

        //把注释编码
        text = text
          .replace(/\n/g, '\r')
          .replace(/<!--(.+?)-->/g, function ($0, text) {
            let ret = '<!--' + escape(text) + '-->'
            return ret
          })
          .replace(/\r/g, '\n')
        //调整格式
        let rgx = /\n(<(([^\\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/gm
        let nodeStack = []
        let output = text.replace(rgx, ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) => {
          let isClosed = isCloseFull1 == '/' || isCloseFull2 == '/' || isFull1 == '/' || isFull2 == '/'
          let prefix = ''
          if (isBegin == '!') {
            prefix = this.getPrefix(nodeStack.length)
          } else {
            if (isBegin != '/') {
              prefix = this.getPrefix(nodeStack.length)
              if (!isClosed) {
                nodeStack.push(name)
              }
            } else {
              nodeStack.pop()
              prefix = this.getPrefix(nodeStack.length)
            }
          }
          let ret = '\n' + prefix + all
          return ret
        })
        let outputText = output.substring(1)
        //把注释还原并解码，调格式
        outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, ($0, prefix, text) => {
          if (prefix.charAt(0) == '\r') prefix = prefix.substring(1)
          text = unescape(text).replace(/\r/g, '\n')
          let ret = '\n' + prefix + '<!--' + text.replace(/^\s*/gm, prefix) + '-->'
          return ret
        })
        outputText = outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n')
        return outputText
      },
      getPrefix(prefixIndex) {
        let span = '    '
        let output = []
        for (let i = 0; i < prefixIndex; ++i) {
          output.push(span)
        }

        return output.join('')
      },
      validateXML(xmlContent) {
        let xmlDoc
        if (document.implementation.createDocument) {
          let parser = new DOMParser()
          xmlDoc = parser.parseFromString(xmlContent, 'text/xml')
          let error = xmlDoc.getElementsByTagName('parsererror')
          if (error.length > 0) {
            return false
          } else {
            return true
          }
        }
      },
      XMLFormat() {
        //XML格式化
        if (!this.validateXML(this.msgResultValue)) this.$baseMessage(translateTitle('Dams.ProcssConfig.XML格式错误'), 'error')
        this.msgResultValue = this.showXml(this.msgResultValue)
      },
      validateJSON(data) {
        if (typeof data == 'string') {
          try {
            var obj = JSON.parse(data)
            if (typeof obj == 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      JSONFormat() {
        //JSON格式化
        if (!this.validateJSON(this.msgResultValue)) return this.$baseMessage(translateTitle('Dams.ProcssConfig.JSON格式错误'), 'error')
        this.msgResultValue = JSON.stringify(JSON.parse(this.msgResultValue), null, 4)
      },
      outMsgConfigAdd(row) {
        //出向报文设置-新增
        this.outMsgConfigData = addRow(this.$refs.outMsgConfigTableRef, this.outMsgConfigData, row, { WEB_DATA_TYPE: 'STRING', ACTIVE_FLAG: true })
      },
      outMsgConfigCopy(row) {
        //出向报文设置-复制
        this.outMsgConfigData = addRow(this.$refs.outMsgConfigTableRef, this.outMsgConfigData, row, row)
      },
      outMsgConfigDel(row) {
        console.log('outMsgConfigDel', this.$refs.outMsgConfigTableRef)
        //出向报文设置-删除
        this.outMsgConfigData = delRow(this.$refs.outMsgConfigTableRef, this.outMsgConfigData, row)
      },
      notDBoutMsgConfigAdd(row, index) {
        this.notDBList[index] = addRow(this.$refs[`DBlevel${index}`][0] || this.$refs[`DBlevel${index}`], this.notDBList[index], row, {
          MESSAGE_TYPE: this.notDBList[index][0].MESSAGE_TYPE,
          ACTIVE_FLAG: true,
          isDisabled: true,
        })
      },
      notDBoutMsgConfigDel(row, index) {
        console.log('outMsgConfigDel', this.$refs[`DBlevel${index}`])
        this.notDBList[index] = delRow(this.$refs[`DBlevel${index}`][0] || this.$refs[`DBlevel${index}`], this.notDBList[index], row)
      },
      targetFieldChange(val, index, rowIndex) {
        this.notDBList[index][rowIndex].XPATH_EXPRESS = './' + val
        // console.log(row, this.notDBList[index][rowIndex].XPATH_EXPRESS, rowIndex)
      },
      backClick() {
        //上一步
        if (this.$store.state.apim.step === 5) {
          if (this.currentIndex === 0) {
            this.$store.dispatch('apim/setStep', 4)
          } else {
            this.outMsgConfigFrom.isChild = this.currentIndex - 2 !== this.DBlevelList.length ?? true
            this.outMsgConfigFrom.MESSAGE_TYPE = this.DBlevelList[this.currentIndex].MESSAGE_TYPE
            if (this.DBlevelList[this.currentIndex - 1]) {
              this.currentLevel = this.totalLevels[this.currentIndex - 1].key
            }
            this.currentIndex--
            this.$store.dispatch('apim/setStep', 5)
            let tabledata = this.DBlevelList[this.currentIndex].JNDI_NAME
            this.outMsgConfigData.forEach((item, index) => {
              if (tabledata[index]) item.STD_FIELD = tabledata[index]
            })
            this.outMsgConfigFrom.WEB_TABLE_NAME = this.levelParamsList[this.currentIndex].WEB_TABLE_NAME
            this.outMsgConfigData = this.levelParamsList[this.currentIndex].data
          }
        } else if (this.$store.state.apim.step === 7) {
          this.isCallBack ? this.$store.dispatch('apim/setStep', 6) : this.$store.dispatch('apim/setStep', 5)
        } else {
          console.log(this.levelParamsList, this.currentIndex)
          if (this.levelParamsList.length > 0) {
            this.outMsgConfigFrom.WEB_TABLE_NAME = this.levelParamsList[this.currentIndex].WEB_TABLE_NAME
            this.outMsgConfigData = this.levelParamsList[this.currentIndex].data
          }
          this.$store.dispatch('apim/setStep', 5)
        }
      },
      boolToString(arr) {
        arr.forEach((item) => {
          if (this.currentIndex === 0) {
            item.ACTIVE_FLAG = item.ACTIVE_FLAG && item.ACTIVE_FLAG == true ? (item.ACTIVE_FLAG = 'Y') : (item.ACTIVE_FLAG = 'N')
            item.KEY_FLAG = item.KEY_FLAG && item.KEY_FLAG == true ? (item.KEY_FLAG = 'Y') : (item.KEY_FLAG = 'N')
            item.UPDATE_FLAG = item.UPDATE_FLAG && item.UPDATE_FLAG == true ? (item.UPDATE_FLAG = 'Y') : (item.UPDATE_FLAG = 'N')
          } else {
            delete item.KEY_FLAG
            delete item.UPDATE_FLAG
            item.ACTIVE_FLAG = item.ACTIVE_FLAG && item.ACTIVE_FLAG == true ? (item.ACTIVE_FLAG = 'Y') : (item.ACTIVE_FLAG = 'N')
          }
          delete item._X_ROW_KEY
        })
        return arr
      },
      uniqueObjList(list, attr) {
        let map = new Map()
        for (let item of list)
          if (!map.has(item[attr])) {
            map.set(item[attr], item)
          }
        list = [...map.values()]
        return list
      },
      setListKey(list, key) {
        let isKey = false
        let count = 0
        for (let i = 0; i < list.length; i++) {
          for (const keys in list[i]) {
            if (keys === key) {
              isKey = true
              count = i
            }
          }
        }
        return { isKey, count }
      },
      async nextClick() {
        //第七步的回显
        if ((this.$store.state.apim.step === 5 && !this.isCallBack && this.currentIndex === 0) || this.$store.state.apim.step === 6) {
          if (this.$store.state.apim.queryData.messageConfigValueList) {
            this.$store.state.apim.queryData.messageConfigValueList.forEach((item) => {
              if (item.TYPE === '11' && item.SN === 1) {
                this.ruleConfigFrom.VALUE_STR01 = item.VALUE_STR01
                this.ruleConfigFrom.VALUE_STR02 = item.VALUE_STR02
                this.ruleConfigFrom.VALUE_STR03 = item.VALUE_STR03
              } else if (item.TYPE === '1' && item.SN === 1) {
                this.ruleConfigFrom.contentType = item.VALUE_STR01
              } else if (item.TYPE === '66' && item.SN === 1) {
                this.ruleConfigFrom.replaceTemp = item.VALUE_STR01
              } else if (item.TYPE === '3') {
                this.httpHeaderList.push({
                  VALUE_STR01: item.VALUE_STR01,
                  VALUE_STR02: item.VALUE_STR02,
                })
              } else if (item.TYPE === '88') {
                this.spaceList.push({
                  VALUE_STR01: item.VALUE_STR01,
                  VALUE_STR02: item.VALUE_STR02,
                })
              } else if (item.TYPE === '14' || item.TYPE === '52' || item.TYPE === '51') {
                this.msgDigestParamsList.push({
                  VALUE_STR01: item.VALUE_STR01,
                  VALUE_STR02: item.VALUE_STR02,
                  VALUE_STR03: item.VALUE_STR03,
                  VALUE_STR04: (item.VALUE_STR04 = item.VALUE_STR04 === 'Y' ?? true),
                  VALUE_STR05: item.VALUE_STR05,
                })
              } else if (item.TYPE === '30') {
                this.postSp = []
                this.postSp.push({
                  VALUE_STR01: item.VALUE_STR01,
                  VALUE_STR02: item.VALUE_STR02,
                  VALUE_STR03: item.VALUE_STR03,
                })
              }
            })

            this.httpHeaderList = this.uniqueObjList(this.httpHeaderList, 'VALUE_STR01')
            this.spaceList = this.uniqueObjList(this.spaceList, 'VALUE_STR01')
            this.msgDigestParamsList = this.uniqueObjList(this.msgDigestParamsList, 'VALUE_STR01')
            console.log(this.$store.state.apim.queryData.messageConfigValueList, this.msgDigestParamsList)
          } else {
            // this.httpHeaderList.push({})
            // this.spaceList.push({})
          }

          if (!this.$store.state.apim.queryData.messageSqlList || this.$store.state.apim.queryData.messageSqlList.length === 0) {
            this.dataFilterRuleList = filterDataList(this.dataFilterRuleList)
            // this.dataFilterRuleList.push({})
          } else {
            this.$store.state.apim.queryData.messageSqlList.forEach((item) => {
              let active_flag = item.ACTIVE_FLAG === 'Y' ?? true
              this.dataFilterRuleList.push({ MESSAGE_TYPE: item.MESSAGE_TYPE, ACTIVE_FLAG: active_flag, SN: item.SN, SQLTEXT: item.SQLTEXT })
            })
          }
          this.dataFilterRuleList = this.uniqueObjList(this.dataFilterRuleList, 'MESSAGE_TYPE')
          let ruleMessageList = this.$store.state.apim.queryData.ruleMessageList
          if (ruleMessageList && ruleMessageList.length > 0) {
            ruleMessageList.forEach((x, i) => {
              this.ruleMessage.RULE_ID[i] = x.RULE_ID
              // this.ruleMessage.RULE_ID.push(x.RULE_ID)
            })
          }
        }
        //下一步
        if (this.$store.state.apim.step === 5) {
          //请求参数
          if (this.isDB) {
            let required = true

            if (this.outMsgConfigData.some((x) => !x.STD_FIELD || (!x.WEB_FIELD && x.ACTIVE_FLAG))) {
              required = false
              this.$baseMessage(translateTitle('Dams.ProcssConfig.来源字段名和目标字段名为必填'), 'error')
            }
            this.$refs['outMsgConfigRef'].validate(async (valid) => {
              if (valid && required === true) {
                if (this.DBlevelList[this.currentIndex + 1]) {
                  this.currentLevel = this.totalLevels[this.currentIndex + 1].key
                }

                let levelParamsList = Object.assign(this.outMsgConfigFrom, { data: this.outMsgConfigData })
                this.levelParamsList[this.currentIndex] = cloneDeep(levelParamsList)
                this.dbData.MAPING_CONFIG = {}
                //有子层级
                if (this.outMsgConfigFrom.isChild) {
                  this.outMsgConfigFrom.isChild = this.currentIndex + 2 !== this.DBlevelList.length ?? true
                  this.outMsgConfigFrom.MESSAGE_TYPE = this.DBlevelList[this.currentIndex].MESSAGE_TYPE

                  let cloneOutMsgConfigData = cloneDeep(this.outMsgConfigData)

                  this.boolToString(cloneOutMsgConfigData)
                  let key = this.outMsgConfigFrom.MESSAGE_TYPE + '_' + this.outMsgConfigFrom.WEB_TABLE_NAME
                  let obj = {}
                  obj[key] = cloneOutMsgConfigData
                  const { isKey, count } = this.setListKey(this.dbList, key)
                  if (isKey) {
                    this.dbList.splice(count, 1)
                  }
                  this.dbList.push(obj)
                  this.currentIndex++
                  this.outMsgConfigData = []
                  this.outMsgConfigFrom.WEB_TABLE_NAME = ''

                  let tabledata = this.DBlevelList[this.currentIndex].JNDI_NAME
                  tabledata.forEach((x, i) => {
                    this.outMsgConfigData[i] = { STD_FIELD: x, WEB_FIELD: x, ACTIVE_FLAG: true }
                  })

                  //第五步DB回显
                  if (this.$store.state.apim.queryData.messageMappingList && this.$store.state.apim.queryData.messageMappingList.length > 0) {
                    this.feedBack()
                  }

                  this.$store.dispatch('apim/setStep', 5)
                  if (this.$store.state.apim.queryData.stdTableList) {
                    let dataform = this.$store.state.apim.queryData.stdTableList
                    this.outMsgConfigFrom.WEB_TABLE_NAME = dataform.find((x) => {
                      return x.MESSAGE_TYPE === this.DBlevelList[this.currentIndex].value
                    })?.WEB_TABLE_NAME
                  }
                  this.outMsgConfigData.forEach((item, index) => {
                    if (tabledata[index]) {
                      item.STD_FIELD = tabledata[index]
                      item.ACTIVE_FLAG = true
                    }
                  })
                } else {
                  //没有子层级
                  this.outMsgConfigFrom.MESSAGE_TYPE = this.DBlevelList[this.currentIndex].MESSAGE_TYPE
                  let cloneOutMsgConfigData = cloneDeep(this.outMsgConfigData)
                  this.boolToString(cloneOutMsgConfigData)
                  let key = this.outMsgConfigFrom.MESSAGE_TYPE + '_' + this.outMsgConfigFrom.WEB_TABLE_NAME
                  let obj = {}
                  obj[key] = cloneOutMsgConfigData
                  const { isKey, count } = this.setListKey(this.dbList, key)
                  if (isKey) {
                    this.dbList.splice(count, 1)
                  }
                  this.dbList.push(obj)
                  let map = new Map()
                  for (let item of this.dbList) {
                    if (!map.has(Object.keys(item)[0])) {
                      map.set(Object.keys(item)[0], item)
                    }
                  }
                  this.dbList = [...map.values()]
                  this.dbData.MAPING_CONFIG = {}
                  this.dbList.forEach((item) => {
                    Object.assign(this.dbData.MAPING_CONFIG, item)
                  })
                  Object.assign(this.dbData, { MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID })
                  try {
                    this.nextLoading = true
                    await apimRequest(`${this.configSetting.domain}/apim/config/stream/outgoingMessageConfiguration`, JSON.stringify(this.dbData), {
                      'Content-Type': 'application/json',
                    })
                    this.nextLoading = false
                    this.isCallBack ? this.$store.dispatch('apim/setStep', 6) : this.$store.dispatch('apim/setStep', 7)
                  } catch (err) {
                    console.log(err)
                  }
                }
              } else {
                return false
              }
            })
          } else {
            //非DB
            let isrequire = false
            let notDBList = cloneDeep(this.notDBList)
            let arr = []
            console.log('test', this.levelParamsList)
            notDBList.forEach((item) => {
              arr.push(item.some((x) => x.ACTIVE_FLAG && x.ACTIVE_FLAG === true && !x.XPATH_EXPRESS))
              item.forEach((x) => {
                x.IS_TRANSFER_FIELD = x.IS_TRANSFER_FIELD && x.IS_TRANSFER_FIELD === true ? (x.IS_TRANSFER_FIELD = 'Y') : (x.IS_TRANSFER_FIELD = 'N')
                x.ACTIVE_FLAG = x.ACTIVE_FLAG && x.ACTIVE_FLAG === true ? (x.ACTIVE_FLAG = 'Y') : (x.ACTIVE_FLAG = 'N')
                // if (x.MESSAGE_FILED !== null) {
                //   x.XPATH_EXPRESS = `./${x.MESSAGE_FILED}`
                // }
              })
            })
            //没有解析，就拿缓存
            if (this.structureConfigMap.length === 0 && this.$store.state.apim.queryData.messageStructureList) {
              let structureConfigMap = this.$store.state.apim.queryData.messageStructureList.filter((item) => {
                return item.ADAPTER_TYPE === 'O'
              })
              if (structureConfigMap.length > 0) {
                this.structureConfigMap = structureConfigMap
              }
            }
            if (this.tableList.length === 0 && this.$store.state.apim.queryData.stdTableList) {
              this.$store.state.apim.queryData.stdTableList.forEach((x) => {
                this.tableList.push({ MESSAGE_TYPE: x.MESSAGE_TYPE })
              })
            }
            notDBList = notDBList.flat(Infinity)
            isrequire = arr.some((x) => x === true)
            // notDBList = notDBList.filter((x) => x.ACTIVE_FLAG !== 'N')
            let outMsgConfigParam = Object.assign(
              { MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID, ADAPTER_TYPE: 'O' },
              { DATA: notDBList, SYS_MESSAGE_STRUCTURE: this.structureConfigMap, SYS_STD_TABLE_LIST: this.tableList }
            )
            try {
              let ADAPTER_TYPE = false
              if (this.$store.state.apim.queryData.messageStructureList && this.$store.state.apim.queryData.messageStructureList.length > 0) {
                ADAPTER_TYPE = this.$store.state.apim.queryData.messageStructureList.some((x) => x.ADAPTER_TYPE === 'O')
              }

              if (this.msgResultValue || ADAPTER_TYPE) {
                if (!isrequire) {
                  this.nextLoading = true
                  await apimRequest(
                    `${this.configSetting.domain}/apim/config/stream/outgoingMessageConfigurations`,
                    JSON.stringify(outMsgConfigParam),
                    {
                      'Content-Type': 'application/json',
                    }
                  )
                  this.nextLoading = false
                  this.isCallBack ? this.$store.dispatch('apim/setStep', 6) : this.$store.dispatch('apim/setStep', 7)
                } else {
                  this.$baseMessage(translateTitle('Dams.ProcssConfig.XPATH表达式必填'), 'error')
                }
              } else {
                this.$baseMessage(translateTitle('Dams.ProcssConfig.未解析报文'), 'error')
              }
            } catch (err) {
              console.log(err)
            }
          }
          //第六步的回显
          if (this.$store.state.apim.queryData.messageConfigList) {
            let { RETURN_MESSAGE_ID, RETURN_CONDITION, RETURN_PARAM1, RETURN_PARAM2, RETURN_PARAM3, RETURN_PARAM4, RETURN_PARAM5 } =
              this.$store.state.apim.queryData.messageConfigList[0]
            this.callbackConfigFrom = {
              RETURN_MESSAGE_ID,
              RETURN_CONDITION,
              RETURN_PARAM1,
              RETURN_PARAM2,
              RETURN_PARAM3,
              RETURN_PARAM4,
              RETURN_PARAM5,
            }
          }
        } else {
          //第六/七步
          this.$refs['callbackConfigRef'].validate(async (valid) => {
            if (valid) {
              try {
                let paramsData = Object.assign(this.callbackConfigFrom, { MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID })
                this.nextLoading = true
                await apimRequest(`${this.configSetting.domain}/apim/config/stream/callbackConfiguration`, JSON.stringify(paramsData), {
                  'Content-Type': 'application/json',
                })
                this.nextLoading = false
                this.$store.dispatch('apim/setStep', 7)
              } catch (err) {
                console.log(err)
              }
            } else {
              return false
            }
          })
        }
        //第七步的下拉数据
        try {
          let { data: msgLevel } = await apimRequest(`${this.configSetting.domain}/apim/config/stream/list/levels`, {
            'Content-Type': 'application/json',
          })
          this.msgLevel = msgLevel
          let { data: signTypes } = await apimRequest(`${this.configSetting.domain}/apim/config/stream/list/signTypes`, {
            'Content-Type': 'application/json',
          })
          this.signTypes = signTypes
          let { data: contentTypes } = await apimRequest(`${this.configSetting.domain}/apim/config/stream/list/contentTypes`, {
            'Content-Type': 'application/json',
          })
          this.contentTypes = contentTypes
          let { data: ruleVerificationQuery } = await apimRequest(`${this.configSetting.domain}/apim/config/stream/ruleVerificationQuery`, {
            'Content-Type': 'application/json',
          })

          this.ruleVerificationQuery = ruleVerificationQuery.rulequery.filter((x) => x.ACTIVE_FLAG === 'Y')
        } catch (err) {
          console.log(err)
        }
      },

      /****************************规则配置***************************/
      filterRuleAdd(row) {
        //过滤规则-新增
        this.dataFilterRuleList = addRow(this.$refs.dataFilterRuleRef, this.dataFilterRuleList, row)
      },
      filterRuleDel(row) {
        //过滤规则-删除
        this.dataFilterRuleList = delRow(this.$refs.dataFilterRuleRef, this.dataFilterRuleList, row)
      },
      msgDigestParamsAdd(row) {
        this.msgDigestParamsList = addRow(this.$refs.msgDigestParamsRef, this.msgDigestParamsList, row)
      },
      msgDigestParamsDel(row) {
        this.msgDigestParamsList = delRow(this.$refs.msgDigestParamsRef, this.msgDigestParamsList, row)
      },
      httpHeaderAdd(row) {
        //httpHeader-新增
        this.httpHeaderList = addRow(this.$refs.httpHeaderRef, this.httpHeaderList, row)
      },
      httpHeaderDel(row) {
        //httpHeader-删除
        this.httpHeaderList = delRow(this.$refs.httpHeaderRef, this.httpHeaderList, row)
      },
      spaceAdd(row) {
        //命名空间-新增
        this.spaceList = addRow(this.$refs.spaceListRef, this.spaceList, row)
      },
      spaceDel(row) {
        //命名空间-删除
        this.spaceList = delRow(this.$refs.spaceListRef, this.spaceList, row)
      },
      publicClick() {
        //发布接口
        //过滤规则
        let FilterRuleList = filterDataList(this.dataFilterRuleList)
        FilterRuleList.forEach((item) => {
          item.ACTIVE_FLAG ? (item.ACTIVE_FLAG = 'Y') : (item.ACTIVE_FLAG = 'N')
        })
        let filterRuleUrlParams = {
          MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID,
          MESSAGE_ID: this.MESSAGE_ID,
          data: FilterRuleList,
        }
        //规则配置
        let filterSpaceList = filterDataList(this.spaceList)
        filterSpaceList = filterSpaceList.map((item, index) => {
          let obj = { SN: index + 1, TYPE: 88 }
          return Object.assign(item, obj)
        })
        let filterhttpHeaderList = filterDataList(this.httpHeaderList)
        filterhttpHeaderList = filterhttpHeaderList.map((item, index) => {
          let obj = { SN: index + 1, TYPE: 3 }
          return Object.assign(item, obj)
        })
        //邮件摘要参数
        let filterMsgDigestParamsList = filterDataList(this.msgDigestParamsList)
        filterMsgDigestParamsList = filterMsgDigestParamsList.map((item, index) => {
          let obj = {
            SN: index + 1,
            TYPE:
              this.$store.state.apim.requiredForm.stepTwoDATA_ACTION == '52' || this.$store.state.apim.requiredForm.stepTwoDATA_ACTION == '51'
                ? this.$store.state.apim.requiredForm.stepTwoDATA_ACTION
                : 14,
          }
          item.VALUE_STR04 = item.VALUE_STR04 ? 'Y' : 'N'
          console.log(item.VALUE_STR04, 'item.VALUE_STR04')
          return Object.assign(item, obj)
        })

        let typeParamData = {
          MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID,
          MESSAGE_ID: this.MESSAGE_ID,
          signature: {
            TYPE: '11',
            SN: '1',
            VALUE_STR01: this.ruleConfigFrom.VALUE_STR01,
            VALUE_STR02: this.ruleConfigFrom.VALUE_STR02,
            VALUE_STR03: this.ruleConfigFrom.VALUE_STR03,
          },
          rearSP: {
            TYPE: '30',
            SN: '1',
            VALUE_STR01: this.postSp[0].VALUE_STR01,
            VALUE_STR02: this.postSp[0].VALUE_STR02,
            VALUE_STR03: this.postSp[0].VALUE_STR03,
          },
          contentType: {
            TYPE: '1',
            SN: '1',
            VALUE_STR01: this.ruleConfigFrom.contentType,
          },
          header: filterhttpHeaderList,
          namespace: filterSpaceList,
          template: {
            TYPE: '66',
            SN: '1',
            VALUE_STR01: this.ruleConfigFrom.replaceTemp,
          },
          mail_summary: filterMsgDigestParamsList,
        }

        if (!typeParamData.signature.VALUE_STR01 || !typeParamData.signature.VALUE_STR02 || !typeParamData.signature.VALUE_STR03) {
          delete typeParamData.signature
        }
        if (typeParamData.rearSP.VALUE_STR01 || typeParamData.rearSP.VALUE_STR02 || typeParamData.rearSP.VALUE_STR03) {
          if (!typeParamData.rearSP.VALUE_STR01 || !typeParamData.rearSP.VALUE_STR02 || !typeParamData.rearSP.VALUE_STR03) {
            // delete typeParamData.rearSP
            this.$message({
              type: 'error',
              message: translateTitle('Dams.ProcssConfig.请将后置SP填写完整'),
            })
            return
          }
        }
        if (!typeParamData.rearSP.VALUE_STR01 && !typeParamData.rearSP.VALUE_STR02 && !typeParamData.rearSP.VALUE_STR03) {
          delete typeParamData.rearSP
        }
        if (!typeParamData.contentType.VALUE_STR01) {
          delete typeParamData.contentType
        }
        if (!typeParamData.template.VALUE_STR01) {
          delete typeParamData.template
        }
        if (typeParamData.header.length === 0) {
          delete typeParamData.header
        }
        if (typeParamData.namespace.length === 0) {
          delete typeParamData.namespace
        }
        //规则校验

        let ruleMessage = []
        this.ruleMessage.RULE_ID.forEach((x, i) => (ruleMessage[i] = { ACTIVE_FLAG: 'Y', RULE_ID: x }))
        console.log(typeParamData)
        let ruleParams = { MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID, data: ruleMessage }

        let typeParamUrl = `${this.configSetting.domain}/apim/config/stream/typeParam`
        let filterRuleUrl = `${this.configSetting.domain}/apim/config/stream/filterRule`
        let ruleParamsUrl = `${this.configSetting.domain}/apim/config/stream/ruleMessage`
        Promise.all([
          apimRequest(typeParamUrl, JSON.stringify(typeParamData), {
            'Content-Type': 'application/json',
          }),
          apimRequest(filterRuleUrl, JSON.stringify(filterRuleUrlParams), {
            'Content-Type': 'application/json',
          }),
          apimRequest(ruleParamsUrl, JSON.stringify(ruleParams), {
            'Content-Type': 'application/json',
          }),
        ])
          .then(async () => {
            this.$store.dispatch('apim/setStep', 8)
            //成功后返回的网址
            let isDB =
              (this.$store.state.apim.requiredForm.stepTwoDATA_ACTION === '40' || this.$store.state.apim.requiredForm.stepTwoDATA_ACTION === '42') ??
              true
            if (isDB) {
              await apimRequest(
                `${this.configSetting.domain}/apim/config/stream/generate/job`,
                JSON.stringify({ MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID }),
                {
                  'Content-Type': 'application/json',
                }
              )
            } else {
              let { data: url } = await apimRequest(
                `${this.configSetting.domain}/apim/config/stream/generate/url`,
                JSON.stringify({ MESSAGE_GROUP_ID: this.MESSAGE_GROUP_ID, MESSAGE_ID: this.MESSAGE_ID }),
                {
                  'Content-Type': 'application/json',
                }
              )
              this.url = `${this.configSetting.domain}${url}`
            }
            //刷新缓存
            await apimRequest(`${this.configSetting.domain}/apim/config/redis/reload`)
          })
          .catch((err) => {
            console.log(err)
          })
      },

      /****************************配置完成***************************/
      reconfigClick() {
        //重新配置
        this.$store.dispatch('apim/setStep', 1)
        this.$store.dispatch('apim/setRequiredForm', {})
        this.$store.dispatch('apim/setQueryData', {})
      },
    },
  }

  //过滤数据
  function filterDataList(list) {
    list.forEach((item) => {
      delete item._X_ROW_KEY
    })
    let filterList = cloneDeep(list)
    return filterList.filter((item) => {
      return Object.keys(item).length !== 0 && Object.values(item).some((x) => x !== null && x !== false && x !== '')
    })
  }
  //添加行
  function addRow(tableref, tableList, row, record = {}) {
    tableref.insertAt(record, row)
    let insertRow = tableref.getInsertRecords()
    tableList = tableList.concat(insertRow)
    return tableList
  }
  //删除行
  function delRow(tableref, tableList, row) {
    console.log('tableref', tableref)
    tableref.remove(row)
    let delRow = tableref.getRemoveRecords()
    tableList = tableList.filter((item) => {
      return !delRow.includes(item)
    })
    return tableList
  }
</script>

<style lang="scss">
  .process {
    margin: 0 60px;
    max-height: calc(100% - 28px);
    overflow: auto;
  }
  .outMsgConfig {
    .queryForm {
      text-align: center;
    }
    .msgSample {
      margin: 10px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      .el-descriptions {
        width: 50%;
        overflow: auto;
      }
      .analysis {
        margin: 10px;
      }
      .cell-item {
        display: flex;
        justify-content: space-between;
      }
    }
    .outMsgConfigTable {
      .operate {
        .el-button + .el-button {
          margin: 0 !important;
          padding: 0 !important;
        }
      }
    }
  }
  .callbackConfig {
    .el-form-item__content {
      width: 200px;
    }
  }
  .ruleConfig {
    .el-form :nth-child(6),
    .el-form :nth-child(7),
    .el-form :nth-child(8) {
      width: calc(100% - 10px);
      .el-form-item--small.el-form-item {
        width: 50%;
        margin: 0 0 18px 0;
      }
    }
    .el-form-item__content {
      width: 200px;
    }
  }
  .success {
    display: flex;
    flex-direction: column;
    align-items: center;
    .img {
      width: 68px;
      height: 68px;
    }
    .title {
      font-weight: 550;
      margin-top: 24px;
      font-size: 18px;
    }

    .content {
      font-size: 16px;
      margin-top: 16px;
    }
  }
  .buttonGroup {
    width: 100%;
    text-align: center;
    margin: 4px;
  }
</style>
